import React, { useEffect, useState } from 'react'
import style from './style.module.scss'
import SubNavbarLayout from '../__Layout__/SubNavLayout'
import SeriesNavbar from '../__Layout__/SubNavLayout/SeriesNavbar'
import GoodsCard from './GoodsCard'
import Collection from '../../transfer/entities/Collection'
import { Pagination } from 'antd'
import Goods from '../../transfer/entities/Goods'
import { pushItem } from '../../utils/RecoilFunction'

export default function Series(props: any) {
    const [collection, setCollection] = useState<any>({})
    const [goods, setGoods] = useState<any>([])
    const [goodsList, setGoodsList] = useState<any>([])

    const loadData = async (page: number) => {
        const collectionsDetails = await new Collection().getCollectionsDetails(props.params.seriesId)
        const goodsIds = await new Collection().getGoodsById(props.params.seriesId, page)

        await setCollection(collectionsDetails.data)
        await setGoods(goodsIds.data.ids)

        let temp: any = []
        goodsIds.data.ids.map((res: any) => {
            new Goods<any>().getGoodsDetails(res).then(item => {
                temp = pushItem(temp, item.data)
                setGoodsList(temp)
            })
        })
    }

    const handlePaginationChange = (page: number, num?: number) => {
        loadData(page)
    }

    useEffect(() => {
        loadData(1)
    }, [])

    return (
        <SubNavbarLayout subNav={<SeriesNavbar title={collection.title} goods={goods.length} />}>
            <div className={style.goods__list}>
                <div className={style.goods__wrap}>
                    {goodsList.map((goods: any, index: number) => (
                        <GoodsCard
                            key={index}
                            id={goods.id}
                            images={goods.shows}
                            title={goods.title}
                            price={goods.skus[0].price}
                            onClick={id => {
                                window.location.href = `/goods/${goods.id}`
                            }}
                        />
                    ))}
                </div>
                <div className={style.goods__pagination}>
                    <Pagination
                        defaultCurrent={1}
                        defaultPageSize={9}
                        total={goods.length}
                        onChange={handlePaginationChange}
                    />
                </div>
            </div>
        </SubNavbarLayout>
    )
}
